<?php

namespace app\club\controller;

use app\common\controller\Clubend;

use think\Controller;
use think\Request;
use think\Session;
use think\Db;
use app\admin\model\CClub;
use function GuzzleHttp\json_decode;
use fast\Http;
use think\Config;

/**
 * 俱乐部管理
 *
 * @icon fa fa-circle-o
 */
class Club extends Clubend
{
    
    /**
     * CClub模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('CClub');
        $this->assign('title','我的俱乐部');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        $uid = Session::get('owner.uid');//游戏ID
        
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $total = $this->model
            ->where($where)
            ->where(['owner'=>$uid,'type'=>2])
            ->order($sort, $order)
            ->count();
    
            $list = $this->model
            ->field('id,owner,name,diamond,members')
            ->where($where)
            ->where(['owner'=>$uid,'type'=>2])
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

            //处理数据
            $clubid_array = [];
            foreach ($list as $val){
                $clubid_array[] = $val['id'];
            }
            //总开房，总荣誉分
            $map['id'] = array('in',$clubid_array);
            $total_info = Db::connect("GameDB")->table('club_total_record')->where($map)->select();
            //今日荣誉分
            $map['date'] = $this->getMilliDate(date('Y-m-d 0:0:0',time()));
            $today_info = Db::connect("GameDB")->table('club_day_record')->where($map)->select();
            //数据处理
            foreach ($total_info as $val){
                $total_array[$val['id']] = $val;
            }
            foreach ($today_info as $val){
                $today_array[$val['id']] = $val;
            }
            //组成
            foreach ($list as $key=>$val){
                $list[$key]['usernum'] = count(json_decode($val['members']));//人数
                $list[$key]['totalnum'] = isset($total_array[$val['id']])?$total_array[$val['id']]['room']:0;//总开房
                $list[$key]['totalscore'] = isset($total_array[$val['id']])?$total_array[$val['id']]['score']:0;//荣誉分
                $list[$key]['todayscore'] = isset($today_array[$val['id']])?$today_array[$val['id']]['score']:0;//今日荣誉分
            }
            $diamond = Db::connect("GameDB")->table('user')->where(['uid'=>$uid])->value('diamond');//剩余房卡
            
            $result = array("total" => $total, "rows" => $list,"diamond"=>$diamond);
    
            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 俱乐部 - 房卡添加
     * @param number $ids 俱乐部ID
     * @author violet
     */
    public function add($ids = 0){
        $row = $this->model->get($ids);
        if (!$row){
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            $diamond = $params['diamond'];
            if($diamond < 100){
                $this->error('单次补充不得小于100房卡');
            }
            $user_diamond = Db::connect("GameDB")->table('user')->where(['uid'=>$this->auth->uid])->value('diamond');//剩余房卡
            if($user_diamond < $diamond){
                $this->error('您的房卡余额不足');
            }
            //游戏服务器数据
            $sreq = [
                'id' => $row['id'],
                'num' => $diamond,
            ];
            //发送给游戏服务器
            $res = Http::get(Config::get('GameDB.api_url').'clubRecharge',$sreq);
            if($res != 'ok')
            {
                $this->error($res);
            }
            $this->success('房卡补充成功，'.$row['name'].'俱乐部补充'.$diamond.'房卡');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
        

}
